package com.gdkm.database.holder;

import com.gdkm.database.enums.DataSourceEnum;

/**
 * @author HD-0078 杨炜耀
 * @date 2021-5-6 16:00
 * 利用ThreadLocal封装的保存数据源上线的上下文context
 */
public class DataSourceContextHolder {

    private static final ThreadLocal<String> context = new ThreadLocal<>();

    /**
     * 赋值
     * @param dataSourceType
     */
    public static void set(String dataSourceType){
        if(dataSourceType == null){
            throw new NullPointerException("dataSourceType not null.");
        }
        context.set(dataSourceType);
    }

    /**
     * 标记为从库
     */
    public static void markSlave(){
        set(DataSourceEnum.SLAVE.getDataSourceName());
    }

    /**
     * 标记为主库
     */
    public static void markMaster(){
        set(DataSourceEnum.MASTER.getDataSourceName());
    }

    /**
     * 获取值
     * @return
     */
    public static String get(){
        return context.get();
    }

    /**
     * 避免内存泄漏
     */
    public static void clear(){
        context.remove();
    }
}
